package com.lc.qianrenshiye.fragments;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lc.qianrenshiye.BaseApplication;
import com.lc.qianrenshiye.R;
import com.lc.qianrenshiye.adapter.AllowanceAdapter;
import com.lc.qianrenshiye.adapter.LoanAdapter;
import com.lc.qianrenshiye.conn.AllowancePost;
import com.lc.qianrenshiye.conn.ChartsDatasGet;
import com.lc.qianrenshiye.conn.LoanPost;
import com.lc.qianrenshiye.dialog.DateTimePickDialogUtil;
import com.lc.qianrenshiye.uitls.MyAnimationUitls;
import com.lc.qianrenshiye.uitls.MyToast;
import com.lc.qianrenshiye.uitls.TimeUtil;
import com.module.pull.PullToRefreshBase;
import com.module.pull.PullToRefreshListView;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.fragment.AppV4Fragment;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.scale.ScaleScreenHelperFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * Created by Administrator on 2016/11/19.
 */
public class FragmentAllowance extends AppV4Fragment implements View.OnClickListener{

    //最上面  已结 未结 当月
    @BoundView(R.id.allowance_not_tv) private TextView allowance_not_tv;
    @BoundView(R.id.allowance_already_tv) private TextView allowance_already_tv;
    @BoundView(R.id.allowance_this_month_tv) private TextView allowance_this_month_tv;

    //三个tab
    @BoundView(R.id.allowance_tab_default_tv) private TextView allowance_tab_default_tv;
    @BoundView(R.id.allowance_tab_time_tv) private TextView allowance_tab_time_tv;
    @BoundView(R.id.allowance_tab_order_tv) private TextView allowance_tab_order_tv;

    //三个tab切换显示的东西
    @BoundView(R.id.default_show_ll) private LinearLayout default_show_ll;
    @BoundView(R.id.allowance_order_rg) private RadioGroup allowance_order_rg;
    @BoundView(R.id.allowance_time_show_rg) private RadioGroup allowance_time_show_rg;
    @BoundView(R.id.allowance_order_show_rg) private RadioGroup allowance_order_show_rg;

    //时间搜索
    @BoundView(R.id.allwance_time_start_tv) private TextView allwance_time_start_tv;
    @BoundView(R.id.allwance_time_end_tv) private TextView allwance_time_end_tv;
    @BoundView(R.id.allwance_search_tv) private TextView allwance_search_tv;

    @BoundView(R.id.allowance_order_all_rb) private RadioButton allowance_order_all_rb;
    @BoundView(R.id.allowance_time_tab_immediate_rb) private RadioButton allowance_time_tab_immediate_rb;
    @BoundView(R.id.allowance_order_show_tab_time_rb) private RadioButton allowance_order_show_tab_time_rb;

    @BoundView(R.id.fragment_allowance_lv) private PullToRefreshListView pullToRefreshListView;
    private ListView fragment_allowance_lv;

    @BoundView(R.id.loan_chart_view) private LineChartView loan_chart_view;// 折线图
    @BoundView(R.id.loan_chart_rl) private RelativeLayout loan_chart_rl;// 折线图布局
    @BoundView(R.id.loan_chart_gone_tv) private TextView loan_chart_gone_tv;// 折线图隐藏按钮

    private List<AllowancePost.AllowanceEntity> lists = new ArrayList<>();

    private AllowanceAdapter adapter;

    private boolean isPullRefresh; //控制 radiobutton 下拉刷新时候改变状态 不让走接口

    private float xDistance , yDistance , xLast , yLast;

//    String[] date = {"5-23","5-22","6-22","5-23","5-22","2-22","5-22","4-22","9-22","10-22","11-22","12-22","1-22","6-22","5-23","5-22","2-22","5-22","4-22","9-22","10-22","11-22","12-22","4-22","9-22","10-22","11-22","zxc"};//X轴的标注
//    int[] score= {74,22,18,79,20,74,20,74,42,90,74,42,90,50,42,90,33,10,74,22,18,79,20,74,22,18,79,20};//图表的数据-

    public List<String> date = new ArrayList<>();
    public List<Integer> score = new ArrayList<>();//图表的数据

    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();

    private ChartsDatasGet chartsDatasGet = new ChartsDatasGet(new AsyCallBack<ChartsDatasGet.ChartsDatasEntity>() {
        @Override
        public void onSuccess(String toast, int type, ChartsDatasGet.ChartsDatasEntity chartsDatasEntity) throws Exception {

            date.addAll(chartsDatasEntity.chartsDates);
            score.addAll(chartsDatasEntity.chartsNums);

            //新的显示方式

            getAxisXLables();//获取x轴的标注
            getAxisPoints();//获取坐标点
            initLineChart();//初始化
        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            MyToast.showToast(toast, getContext());
        }
    });

    private AllowancePost allowancePost = new AllowancePost(new AsyCallBack<AllowancePost.AllowanceListEntity>() {

        @Override
        public void onSuccess(String toast, int type, AllowancePost.AllowanceListEntity allowanceListEntity) throws Exception {


            allowance_this_month_tv.setText(allowanceListEntity.total);
            allowance_already_tv.setText(allowanceListEntity.knot);
            allowance_not_tv.setText(allowanceListEntity.nkont);

            //其实都清空，就加载时候不清空
            if (type == 0) {

                lists.clear();

            } else if (type == 1) { //第一次进来走接口type == 1

                lists.clear();

                MyAnimationUitls.toVisibleAnim(fragment_allowance_lv);

            } else if (type == 2) { //刷新走接口type == 2

                lists.clear();

                isPullRefresh = true;

                allwance_time_start_tv.setText("");
                allwance_time_end_tv.setText("");

                allowance_order_all_rb.setChecked(true);
                allowance_time_tab_immediate_rb.setChecked(true);
                allowance_order_show_tab_time_rb.setChecked(true);
            }

            lists.addAll(allowanceListEntity.allowanceEntityList);

            if (lists.size() == 0) {

                AllowancePost.AllowanceEntity allowanceEntity = new AllowancePost.AllowanceEntity();

                allowanceEntity.sub_state = "";
                allowanceEntity.id = "";
                allowanceEntity.ordersn = "";
                allowanceEntity.posttime = "";
                allowanceEntity.sub_money = "";
                allowanceEntity.sub_time = "";
                allowanceEntity.subsidies = "";

                lists.add(allowanceEntity);
            }

            adapter.notifyDataSetChanged();

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            MyToast.showToast(toast, getContext());
        }

        @Override
        public void onEnd(String toast, int type) throws Exception {

            pullToRefreshListView.onPullUpRefreshComplete();
            pullToRefreshListView.onPullDownRefreshComplete();

            setLastUpdateTime();

        }
    });

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = BoundViewHelper.boundView(FragmentAllowance.this, inflater.inflate(R.layout.fragment_allowance, null));

        View headView = BoundViewHelper.boundView(this, ScaleScreenHelperFactory.getInstance().loadView((ViewGroup) inflater.inflate(R.layout.fragment_allowance_header, null)));

        pullToRefreshListView.setScrollLoadEnabled(false);
        pullToRefreshListView.setPullLoadEnabled(true);
        pullToRefreshListView.setPullRefreshEnabled(true);

        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                allowancePost.sid = BaseApplication.BasePreferences.readShopId();
                allowancePost.pay = "";
                allowancePost.time = "day";
                allowancePost.type = "subsidies";
                allowancePost.start = "";
                allowancePost.end = "";
                allowancePost.execute(getActivity(), false, 2);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

//                allowancePost.execute(getActivity(), false);
                pullToRefreshListView.onPullUpRefreshComplete();

            }
        });

        fragment_allowance_lv = pullToRefreshListView.getRefreshableView();

        fragment_allowance_lv.setVisibility(View.GONE);

        fragment_allowance_lv.addHeaderView(headView, null, false);

        fragment_allowance_lv.setFocusable(false);
        fragment_allowance_lv.setDivider(null);
        fragment_allowance_lv.setVerticalScrollBarEnabled(false);
        fragment_allowance_lv.setAdapter(adapter = new AllowanceAdapter(getActivity(), lists));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        allwance_time_start_tv.setHint(simpleDateFormat.format(new Date()).toString());
        allwance_time_end_tv.setHint(simpleDateFormat.format(new Date()).toString());

        allowance_order_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {

                    case R.id.allowance_order_all_rb:

                        allowance_tab_default_tv.setText("筛选：全部");

                        if (isPullRefresh) {

                            return;

                        }

                        allowancePost.pay = "";
                        allowancePost.execute(getActivity(), true);

                        break;

                    case R.id.allowance_order_had_rb:

                        allowance_tab_default_tv.setText("筛选：已提");

                        allowancePost.pay = "1";
                        allowancePost.execute(getActivity(), true);

                        break;

                    case R.id.allowance_order_nohad_rb:

                        allowance_tab_default_tv.setText("筛选：未提");

                        allowancePost.pay = "-1";
                        allowancePost.execute(getActivity(), true);

                        break;

                }
            }
        });

        allowance_time_show_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {

                    case R.id.allowance_time_tab_immediate_rb:

                        allowance_tab_time_tv.setText("列表数据：即时");

                        if (isPullRefresh) {

                            return;

                        }

                        allowancePost.start = "";
                        allowancePost.end = "";
                        allowancePost.time = "day";
                        allowancePost.execute(getActivity(), true);

                        break;

                    case R.id.allowance_time_tab_day_rb:

                        allowance_tab_time_tv.setText("列表数据：一天");

                        allowancePost.start = "";
                        allowancePost.end = "";
                        allowancePost.time = "day";
                        allowancePost.execute(getActivity(), true);

                        break;

                    case R.id.allowance_time_tab_month_rb:

                        allowance_tab_time_tv.setText("列表数据：月份");

                        allowancePost.start = "";
                        allowancePost.end = "";
                        allowancePost.time = "time";
                        allowancePost.execute(getActivity(), true);

                        break;

                    case R.id.allowance_time_tab_year_rb:

                        allowance_tab_time_tv.setText("列表数据：年份");

                        allowancePost.start = "";
                        allowancePost.end = "";
                        allowancePost.time = "year";
                        allowancePost.execute(getActivity(), true);

                        break;

                }
            }
        });



        allowance_order_show_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {

                    case R.id.allowance_order_show_tab_time_rb:

                        allowance_tab_order_tv.setText("排序：按时间");

                        if (isPullRefresh) {

                            isPullRefresh = false;

                            return;
                        }

                        allowancePost.type = "time";
                        allowancePost.execute(getActivity(), true);
                        break;

                    case R.id.allowance_order_show_tab_money_rb:

                        allowance_tab_order_tv.setText("排序：按金额");

                        allowancePost.type = "subsidies";
                        allowancePost.execute(getActivity(), true);

                        break;
                }
            }
        });



        allowancePost.sid = BaseApplication.BasePreferences.readShopId();
        allowancePost.pay = "";
        allowancePost.time = "day";
        allowancePost.type = "subsidies";
        allowancePost.start = "";
        allowancePost.end = "";
        allowancePost.execute(getActivity(), 1);

        chartsDatasGet.sid = BaseApplication.BasePreferences.readShopId();
        chartsDatasGet.type = "subsidies";
        chartsDatasGet.execute(getActivity(), false);

        loan_chart_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        xDistance = yDistance = 0f;
                        xLast = event.getX();
                        yLast = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        final float curX = event.getX();
                        final float curY = event.getY();

                        xDistance += Math.abs(curX - xLast);
                        yDistance += Math.abs(curY - yLast);
                        xLast = curX;
                        yLast = curY;

                        if (xDistance > yDistance) {

                            //不允许ScrollView截断点击事件，点击事件由子View处理
                            fragment_allowance_lv.requestDisallowInterceptTouchEvent(true);

                        }

                }

                return false;

            }
        });

        allowance_tab_default_tv.setOnClickListener(this);
        allowance_tab_time_tv.setOnClickListener(this);
        allowance_tab_order_tv.setOnClickListener(this);

        allwance_time_start_tv.setOnClickListener(this);
        allwance_time_end_tv.setOnClickListener(this);
        allwance_search_tv.setOnClickListener(this);
        loan_chart_gone_tv.setOnClickListener(this);

        return view;
    }


    @Override
    public void onClick(View v) {

        DateTimePickDialogUtil dateUtil;

        switch (v.getId()) {

            case R.id.loan_chart_gone_tv:

                loan_chart_rl.setVisibility(View.GONE);

                break;

            case R.id.allowance_tab_default_tv:

                allowance_tab_default_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_choose_bg_color));
                allowance_tab_time_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_bg_color));
                allowance_tab_order_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_bg_color));

                default_show_ll.setVisibility(View.VISIBLE);
                allowance_time_show_rg.setVisibility(View.GONE);
                allowance_order_show_rg.setVisibility(View.GONE);

                break;

            case R.id.allowance_tab_time_tv:

                allowance_tab_default_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_bg_color));
                allowance_tab_time_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_choose_bg_color));
                allowance_tab_order_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_bg_color));

                default_show_ll.setVisibility(View.GONE);
                allowance_time_show_rg.setVisibility(View.VISIBLE);
                allowance_order_show_rg.setVisibility(View.GONE);

                break;

            case R.id.allowance_tab_order_tv:

                allowance_tab_default_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_bg_color));
                allowance_tab_time_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_bg_color));
                allowance_tab_order_tv.setBackgroundColor(getResources().getColor(R.color.income_tab_choose_bg_color));

                default_show_ll.setVisibility(View.GONE);
                allowance_time_show_rg.setVisibility(View.GONE);
                allowance_order_show_rg.setVisibility(View.VISIBLE);

                break;

            case R.id.allwance_time_start_tv:

                dateUtil = new DateTimePickDialogUtil(getActivity(), null);

                dateUtil.dateTimePicKDialog(allwance_time_start_tv);

                break;

            case R.id.allwance_time_end_tv:

                dateUtil = new DateTimePickDialogUtil(getActivity(), null);

                dateUtil.dateTimePicKDialog(allwance_time_end_tv);

                break;

            case R.id.allwance_search_tv:

                String startTime = allwance_time_start_tv.getText().toString();
                String entTime = allwance_time_end_tv.getText().toString();

                if (TextUtils.isEmpty(startTime)) {

                    MyToast.showToast("请选择开始时间", getActivity());
                    return;

                } else if (TextUtils.isEmpty(entTime)){

                    MyToast.showToast("请选择结束时间", getActivity());
                    return;

                }

                if (Long.valueOf(TimeUtil.dataOne(entTime)) - Long.valueOf(TimeUtil.dataOne(startTime)) < 0) {

                    MyToast.showToast("起始时间 大于 结束时间", getActivity());

                    return;
                }

                allowancePost.pay = "";
                allowancePost.time = "";
                allowancePost.type = "subsidies";
                allowancePost.start = startTime;
                allowancePost.end = entTime;
                allowancePost.execute(getActivity(), true);

                break;

        }


    }

    /**
     * 初始化LineChart的一些设置
     */
    private void initLineChart(){
        Line line = new Line(mPointValues).setColor(Color.parseColor("#d98636"));  //折线的颜色
        List<Line> lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(false);//曲线是否平滑
        line.setStrokeWidth(1);//线条的粗细，默认是3
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(false);//曲线的数据坐标是否加上备注
//		line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(false);//是否显示圆点 如果为false 则没有原点只有点显示
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(false);  //X轴下面坐标轴字体是斜的显示还是直的，true是斜的显示
	    axisX.setTextColor(ContextCompat.getColor(getContext(), R.color.text_hint_color));  //设置字体颜色

//	    axisX.setName("未来几天的天气");  //表格名称
        axisX.setTextSize(11);//设置字体大小
        axisX.setMaxLabelChars(7); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
//	    data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(false); //x 轴分割线

        Axis axisY = new Axis();  //Y轴
        axisY.setName("");//y轴标注
        axisY.setTextSize(11);//设置字体大小
        axisY.setTextColor(ContextCompat.getColor(getContext(), R.color.text_hint_color));  //设置字体颜色
        data.setAxisYLeft(axisY);  //Y轴设置在左边
//        data.setAxisYRight(axisY);  //y轴设置在右边
        //设置行为属性，支持缩放、滑动以及平移
        loan_chart_view.setInteractive(true);
        loan_chart_view.setZoomType(ZoomType.HORIZONTAL);  //缩放类型，水平
        loan_chart_view.setMaxZoom((float) 4);//缩放比例
        loan_chart_view.setLineChartData(data);
        loan_chart_view.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 尼玛搞的老子好辛苦！！！见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         * 下面几句可以设置X轴数据的显示个数（x轴0-7个数据），当数据点个数小于（29）的时候，缩小到极致hellochart默认的是所有显示。当数据点个数大于（29）的时候，
         * 若不设置axisX.setMaxLabelChars(int count)这句话,则会自动适配X轴所能显示的尽量合适的数据个数。
         * 若设置axisX.setMaxLabelChars(int count)这句话,
         * 33个数据点测试，若 axisX.setMaxLabelChars(10);里面的10大于v.right= 7; 里面的7，则
         刚开始X轴显示7条数据，然后缩放的时候X轴的个数会保证大于7小于10
         若小于v.right= 7;中的7,反正我感觉是这两句都好像失效了的样子 - -!
         * 并且Y轴是根据数据的大小自动设置Y轴上限
         * 若这儿不设置 v.right= 7; 这句话，则图表刚开始就会尽可能的显示所有数据，交互性太差
         */
        Viewport v = new Viewport(loan_chart_view.getMaximumViewport());
        v.left = 0;
        v.right= 7;
        loan_chart_view.setCurrentViewport(v);
    }

    /**
     * X 轴的显示
     */
    private void getAxisXLables(){
        for (int i = 0; i < date.size(); i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(date.get(i)));
        }
    }
    /**
     * 图表的每个点的显示
     */
    private void getAxisPoints(){
        for (int i = 0; i < score.size(); i++) {
            mPointValues.add(new PointValue(i, score.get(i)));
        }

        for (int i = score.size(); i < score.size() + 3; i++) {

            mPointValues.add(new PointValue(i, 0));

        }
//
//        mPointValues.add(new PointValue(1, 2));
//        mPointValues.add(new PointValue(2, 6));
//        mPointValues.add(new PointValue(3, 0));
//        mPointValues.add(new PointValue(4, 0));
//        mPointValues.add(new PointValue(5, 0));
//        mPointValues.add(new PointValue(6, 0));

    }

    private void setLastUpdateTime() {

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String time = sDateFormat.format(System.currentTimeMillis());

        pullToRefreshListView.setLastUpdatedLabel(time);

    }


}
